package cn.lg.soar.system.auth.controller;

import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.ManyToManyDTO;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.core.annotations.IdempotentByParam;
import cn.lg.soar.core.annotations.constraints.Id;
import cn.lg.soar.database.base.controller.BaseController;
import cn.lg.soar.database.query.QueryParams;
import cn.lg.soar.database.query.SqueryWapper;
import cn.lg.soar.database.util.MpSqlUtils;
import cn.lg.soar.database.util.PageUtils;
import cn.lg.soar.mvc.annotations.*;
import cn.lg.soar.system.api.constant.ModuleConst;
import cn.lg.soar.system.auth.entity.Org;
import cn.lg.soar.system.auth.model.OrgDto;
import cn.lg.soar.system.auth.model.OrgTree;
import cn.lg.soar.system.auth.service.IOrgService;
import cn.lg.soar.system.auth.service.OrgRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * @author luguoxiang
 * @date 2021/8/21
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Validated
@Api(tags = "组织机构")
@RestController
@RequestMapping(ModuleConst.MODULE_NAME + "/org")
public class OrgController  extends BaseController<Org, IOrgService> {

    @Override
    protected Serializable getId(Org entity) {
        return entity.getId();
    }

    @Autowired
    private OrgRoleService orgRoleService;

    private final static String SUBJECT = "组织机构";

    @Log(value = "新增" + SUBJECT, data = "#p0", dataId = "#$r.data")
    @IdempotentByParam("#p0")
    @CreateMapping
    public HttpResult<Serializable> create(@RequestBody @Validated OrgDto entity) {
        return HttpResult.<Serializable>success("创建组织机构成功")
                .setData(this.service.create(entity));
    }

    @Log(value = "修改" + SUBJECT, data = "#p0", dataId = "#p0.id")
    @UpdateMapping
    public HttpResult<Void> update(@RequestBody @Validated Org entity) {
        return super.updateResult(entity);
    }

    @Log(value = "删除" + SUBJECT, data = "#p0", type = Log.Type.TEXT)
    @RemoveMapping
    public HttpResult<Void> remove(@RequestBody List<Long> ids) {
        return super.removeResult(ids);
    }

    @DetailMapping
    public HttpResult<Org> detail(@Id Long id) {
        return super.detailResult(id);
    }

    @QueryMapping
    public HttpResult<PageResult<Org>> query(PageQuery pageQuery, QueryParams params, Long[] roleIds, Long[] userIds, Long[] postIds){
        QueryWrapper<Org> wrapper = new SqueryWapper<>(Org.class).listWrapper(params);
        MpSqlUtils.handleInOrEq(roleIds, (sql, value) -> {
            wrapper.exists("select * from lg_sys_org_2_role r where lg_sys_org.id=r.org_id and r.role_id " + sql, value);
        });
        MpSqlUtils.handleInOrEq(userIds, (sql, value) -> {
            wrapper.exists("select * from lg_sys_user_2_org u where lg_sys_org.id=u.org_id and u.user_id " + sql, value);
        });
        MpSqlUtils.handleInOrEq(postIds, (sql, value) -> {
            wrapper.exists("select * from lg_sys_post p where lg_sys_org.id=p.org_id and p.id " + sql, value);
        });
        IPage<Org> page = service.page(PageUtils.toPage(pageQuery), wrapper);
        return HttpResult.data(PageUtils.toPageResult(page));
    }

    @ListMapping
    public HttpResult<List<Org>> list(QueryParams params){
        return HttpResult.data(
                super.getList(params)
        );
    }

    @ExistMapping
    public HttpResult<Boolean> exist(QueryParams params){
        return super.existResult(params);
    }

    @Log(value = "导出" + SUBJECT, data = "#p0")
    @ExportMapping
    public void exports(QueryParams params, HttpServletResponse resp){
        super.exportExcel(OrgController.SUBJECT, params, resp);
    }

    @Log(value = "导入" + SUBJECT)
    @ImportMapping
    public HttpResult<Void> imports(HttpServletRequest req){
        return super.importExcel(req);
    }

    @ApiOperation("清空缓存")
    @PostMapping(value = "clear-cache", name = "清空缓存")
    public HttpResult<Void> clearCache(){
        this.service.clearCache();
        return HttpResult.success();
    }

    @ApiOperation("设置组织角色")
    @PostMapping(value = "set-role-ids")
    public HttpResult<Void> setRoleIds(@RequestBody @Validated ManyToManyDTO<Long, Long> dto){
        List<Long> bIds = dto.getBids();
        for (Long aId : dto.getAids()) {
            orgRoleService.setOrgRole(aId, bIds);
        }
        return HttpResult.success();
    }

    @ApiOperation("获取组织角色id")
    @GetMapping(value = "get-role-ids")
    public HttpResult<List<Long>> getRoleIds(@RequestParam Long orgId){
        List<Long> ids = orgRoleService.getRoleIds(orgId);
        return HttpResult.data(ids);
    }

    @ApiOperation("根据id获取名称链路")
    @GetMapping(value = "nameLinkByIds")
    public HttpResult<Map<Long, List<String>>> nameLinkByIds(@RequestParam List<Long> ids){
        return HttpResult.data(
                service.nameLinkByIds(ids)
        );
    }

    @ApiOperation("树形数据")
    @GetMapping(value = "tree")
    public HttpResult<List<OrgTree>> tree(Long parentId){
        return HttpResult.data(
                service.tree(parentId)
        );
    }

}
